<?php
namespace App\Model\User;
use PhalApi\Model\DataModel;

class User extends DataModel {

    protected function getTableName($id) {
        return 'phalapi_user';
    }

    public function getInfo($userId) {
        return $this->getORM()->select('*')->where('id = ?', $userId)->fetch();
    }

    public function updateByUsername($username, $password, $moreInfo = array()) {
        $newUserInfo = $moreInfo;
        $newUserInfo['username'] = $username;
        if ( $password ){
            $newUserInfo['salt'] = \PhalApi\Tool::createRandStr(32);
            // $newUserInfo['password'] = $this->encryptPassword($password, $newUserInfo['salt']);
            // 以后用明文密码，方便管理，主要现在这密码不可逆
            $newUserInfo['password'] = $password;
        }
        $newUserInfo['update_time'] = date("Y-m-d H:i:s", time());
        $update_res = $this->getORM()->where('username', $username)->update($newUserInfo);
        return $update_res;
    }

    // 密码加密算法
    public function encryptPassword($password, $salt) {
        return md5(md5(\PhalApi\DI()->config->get('phalapi_user.common_salt')) . md5($password) . sha1($salt));
    }

    /**
     * 批量获取用户快照，并进行反转，以便外部查找
     */
    public function getSnapshotByUserIds(array $userIds)
    {
        $rs = array();
        if (empty($userIds)) {
            return $rs;
        }

        $rows =self::getORM()
            ->select('id,nickname,avatar')
            ->where('id', $userIds)
            ->fetchAll();

        foreach ($rows as $row) {
            $rs[$row['id']] = $row;
        }

        return $rows;
    }
}